/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

//Here we copy the external database to a new one to use it
public class OpenDB extends SQLiteOpenHelper {

	// The Android's default system path of your application database.
	private static String DB_PATH = "/data/data/com.example.androball_manager/databases/";

	private static String DB_NAME = "database";

	private SQLiteDatabase myDataBase;

	private final Context myContext;

	// FOR THE TEAMS TABLE
	public static final String table1 = "teams";
	public static final String id = "_id";
	public static final String name = "name";
	public static final String rating = "rating";
	public static final String selected = "selected";

	// FOR THE PLAYERS TABLE
	public static final String table2 = "players";
	public static final String position = "position";
	public static final String team = "team";

	// FOR THE GAMES
	public static final String table3 = "gameplan";
	public static final String game_home = "id_home";
	public static final String game_away = "id_away";
	public static final String score_home = "score_home";
	public static final String score_away = "score_away";
	public static final String gameday = "id_gameday";

	// FOR THE TABLE
	public static final String table4 = "leaderboard";
	public static final String games_played = "games_played";
	public static final String won_matches = "won_matches";
	public static final String draw_matches = "draw_matches";
	public static final String lost_matches = "lost_matches";
	public static final String points = "points";

	/**
	 * Constructor Takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 * 
	 * @param context
	 */
	public OpenDB(Context context) {

		super(context, DB_NAME, null, 1);
		this.myContext = context;
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
			Log.e("database", "Database exists (createDataBase)");

		} else {

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.

			Log.e("database", "Database doesn't exist (createDataBase)");
			this.getReadableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		boolean checkdb = false;
		try {
			String myPath = myContext.getFilesDir().getAbsolutePath()
					.replace("files", "databases")
					+ File.separator + DB_NAME;
			File dbfile = new File(myPath);
			checkdb = dbfile.exists();
			Log.e("database", "Database exists (checkDataBase)");

		} catch (SQLiteException e) {
			Log.e("database", "Database doesn't exist yet (checkDataBase)");
			// database does't exist yet.
		}

		return checkdb;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		Log.e("database", "Starting to copy...");

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		Log.e("database", "Database ready");
		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	public void openDataBase() throws SQLException {

		// Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);

	}

	@Override
	public synchronized void close() {

		if (myDataBase != null)
			myDataBase.close();

		super.close();

	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}
